package com.xiaotao.groovy.service;

import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;
import org.codehaus.groovy.runtime.GStringImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import java.io.InputStreamReader;

@Service
public class HelloService {

    @javax.annotation.Resource
    private ApplicationContext context;

    public String sayHello(String name) throws Exception {
        Resource script = context.getResource("classpath:scripts/hello.groovy");
        GroovyScriptEngineFactory factory = new GroovyScriptEngineFactory();
        ScriptEngine engine = factory.getScriptEngine();
        engine.eval(new InputStreamReader(script.getInputStream()));
        Invocable invocable = (Invocable) engine;


//      GStringImpl obj = (GStringImpl)invocable.invokeFunction("sayHello",name);
        GStringImpl obj = (GStringImpl) invocable.invokeFunction("sayHi", name);

        String ret = obj.toString();
        System.out.println(ret);
        return ret;
    }
}
